import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:xingsu/util/use_preferences.dart';

import '../../video/model/Video_model.dart';

class GameSearchViewModel extends GetxController {
  final TextEditingController controller = TextEditingController();
  final List<VideoModel> allList;

  GameSearchViewModel(this.allList);

  final list = [].obs;
  final historys = <String>[].obs;

  final FocusNode focusNode = FocusNode();
  final hasFocus = false.obs;

  @override
  void onInit() {
    super.onInit();

    focusNode.addListener(() {
      hasFocus.value = focusNode.hasFocus;
      print(hasFocus.value);
    });

    _loadJ();
  }

  void _loadJ() async {
    String jsonData = await rootBundle.loadString('assets/json/his.json');
    List allList = json.decode(jsonData);
    for (Map map in allList) {
      VideoModel model = VideoModel.fromJson(map);
      this.allList.add(model);
    }

    historys.assignAll(UserPreferences.getSearchHistory());
    print(historys);
  }

  void delHistory(String history) {
    historys.remove(history);
    UserPreferences.setSearchHistory(historys.toList());
  }

  void search() {
    if (controller.text.isEmpty) {
      return;
    }

    focusNode.unfocus();

    List _datas = [];
    for (VideoModel model in allList) {
      if ((model.gameTitle ?? "") == controller.text) {
        _datas.add(model);
      }
    }

    list.assignAll(_datas);

    if (list.isEmpty) {
      Fluttertoast.showToast(msg: "结果为空");
    } else {
      List<String> historys = UserPreferences.getSearchHistory();
      if (historys.contains(controller.text)) {
        historys.remove(controller.text);
        historys.insert(0, controller.text);
      } else {
        historys.insert(0, controller.text);
      }
      UserPreferences.setSearchHistory(historys);
      this.historys.assignAll(historys);
    }
  }
}
